"use client"

import { useState } from "react"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Separator } from "@/components/ui/separator"
import { ChevronDown, ChevronRight, Copy, Download, Eye, Code2 } from "lucide-react"
import { useToast } from "@/hooks/use-toast"
import type { GeneratedLangGraphCode, LayeredCode } from "@/lib/langgraph-generator"

interface LayeredCodeViewerProps {
  generatedCode: GeneratedLangGraphCode
}

export function LayeredCodeViewer({ generatedCode }: LayeredCodeViewerProps) {
  const { toast } = useToast()
  const [expandedLayers, setExpandedLayers] = useState<Set<string>>(new Set(["Layer 4"]))
  const [viewMode, setViewMode] = useState<"layered" | "full">("layered")

  const toggleLayer = (layerName: string) => {
    const newExpanded = new Set(expandedLayers)
    if (newExpanded.has(layerName)) {
      newExpanded.delete(layerName)
    } else {
      newExpanded.add(layerName)
    }
    setExpandedLayers(newExpanded)
  }

  const expandAll = () => {
    setExpandedLayers(new Set(generatedCode.layers.map((l) => l.layer)))
  }

  const collapseAll = () => {
    setExpandedLayers(new Set())
  }

  const copyToClipboard = async (code: string, layerName?: string) => {
    try {
      await navigator.clipboard.writeText(code)
      toast({
        title: "复制成功",
        description: layerName ? `${layerName} 代码已复制到剪贴板` : "完整代码已复制到剪贴板",
      })
    } catch (err) {
      toast({
        title: "复制失败",
        description: "请手动复制代码",
        variant: "destructive",
      })
    }
  }

  const downloadCode = () => {
    const blob = new Blob([generatedCode.fullCode], { type: "text/plain;charset=utf-8" })
    const url = URL.createObjectURL(blob)
    const a = document.createElement("a")
    a.href = url
    a.download = `langgraph_workflow_${Date.now()}.py`
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    URL.revokeObjectURL(url)
    toast({
      title: "下载成功",
      description: "LangGraph 代码已下载",
    })
  }

  return (
    <div className="flex flex-col gap-4 h-full">
      {/* 工具栏 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <Badge variant="outline" className="gap-1">
            <Code2 className="h-3 w-3" />
            {generatedCode.summary.nodeCount} 节点 · {generatedCode.summary.edgeCount} 连接
          </Badge>
          <Separator orientation="vertical" className="h-4" />
          <Button variant="ghost" size="sm" onClick={expandAll}>
            展开全部
          </Button>
          <Button variant="ghost" size="sm" onClick={collapseAll}>
            折叠全部
          </Button>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" size="sm" onClick={() => copyToClipboard(generatedCode.fullCode)}>
            <Copy className="mr-2 h-4 w-4" />
            复制全部
          </Button>
          <Button variant="outline" size="sm" onClick={downloadCode}>
            <Download className="mr-2 h-4 w-4" />
            下载代码
          </Button>
        </div>
      </div>

      {/* 视图切换 */}
      <Tabs value={viewMode} onValueChange={(v) => setViewMode(v as any)} className="flex-1 flex flex-col min-h-0">
        <TabsList className="grid w-full max-w-md grid-cols-2">
          <TabsTrigger value="layered">分层视图</TabsTrigger>
          <TabsTrigger value="full">完整代码</TabsTrigger>
        </TabsList>

        {/* 分层视图 */}
        <TabsContent value="layered" className="flex-1 mt-4 min-h-0">
          <ScrollArea className="h-full">
            <div className="space-y-3 pr-4">
              {generatedCode.layers.map((layer) => (
                <LayerCard
                  key={layer.layer}
                  layer={layer}
                  isExpanded={expandedLayers.has(layer.layer)}
                  onToggle={() => toggleLayer(layer.layer)}
                  onCopy={() => copyToClipboard(layer.code, layer.layer)}
                />
              ))}
            </div>
          </ScrollArea>
        </TabsContent>

        {/* 完整代码视图 */}
        <TabsContent value="full" className="flex-1 mt-4 min-h-0">
          <Card className="h-full flex flex-col">
            <CardHeader className="pb-3">
              <div className="flex items-center justify-between">
                <div>
                  <CardTitle className="text-base">完整代码</CardTitle>
                  <CardDescription>所有层级的完整 LangGraph 代码</CardDescription>
                </div>
                <Button variant="outline" size="sm" onClick={() => copyToClipboard(generatedCode.fullCode)}>
                  <Copy className="mr-2 h-4 w-4" />
                  复制
                </Button>
              </div>
            </CardHeader>
            <CardContent className="flex-1 p-0 min-h-0">
              <ScrollArea className="h-full">
                <pre className="p-4 text-xs font-mono bg-muted/30 rounded-none whitespace-pre-wrap break-words">
                  <code>{generatedCode.fullCode}</code>
                </pre>
              </ScrollArea>
            </CardContent>
          </Card>
        </TabsContent>
      </Tabs>
    </div>
  )
}

interface LayerCardProps {
  layer: LayeredCode
  isExpanded: boolean
  onToggle: () => void
  onCopy: () => void
}

function LayerCard({ layer, isExpanded, onToggle, onCopy }: LayerCardProps) {
  return (
    <Card
      className="overflow-hidden transition-all"
      style={{
        borderLeft: `4px solid ${layer.color}`,
      }}
    >
      <CardHeader className="pb-3">
        <div className="flex items-start justify-between gap-2">
          <button onClick={onToggle} className="flex-1 flex items-start gap-2 text-left hover:opacity-70 transition">
            {isExpanded ? <ChevronDown className="h-5 w-5 shrink-0 mt-0.5" /> : <ChevronRight className="h-5 w-5 shrink-0 mt-0.5" />}
            <div className="flex-1 min-w-0">
              <div className="flex items-center gap-2 mb-1">
                <Badge variant="outline" className="shrink-0">
                  {layer.layer}
                </Badge>
                <CardTitle className="text-base truncate">{layer.title}</CardTitle>
              </div>
              <CardDescription className="text-xs">{layer.description}</CardDescription>
            </div>
          </button>
          <Button variant="ghost" size="icon" className="h-8 w-8 shrink-0" onClick={onCopy}>
            <Copy className="h-4 w-4" />
          </Button>
        </div>
      </CardHeader>

      {isExpanded && (
        <CardContent className="pt-0">
          <div className="rounded-md bg-muted/30 border">
            <ScrollArea className="max-h-[500px]">
              <pre className="p-4 text-xs font-mono whitespace-pre-wrap break-words">
                <code>{layer.code}</code>
              </pre>
            </ScrollArea>
          </div>
        </CardContent>
      )}
    </Card>
  )
}

interface LayeredCodeSummaryProps {
  summary: GeneratedLangGraphCode["summary"]
}

export function LayeredCodeSummary({ summary }: LayeredCodeSummaryProps) {
  return (
    <Card>
      <CardHeader className="pb-3">
        <CardTitle className="text-sm">代码统计</CardTitle>
      </CardHeader>
      <CardContent>
        <div className="space-y-2 text-sm">
          <div className="flex justify-between">
            <span className="text-muted-foreground">节点数量:</span>
            <span className="font-medium">{summary.nodeCount}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-muted-foreground">连接数量:</span>
            <span className="font-medium">{summary.edgeCount}</span>
          </div>
          <div className="flex justify-between">
            <span className="text-muted-foreground">架构层级:</span>
            <span className="font-medium">{summary.layers.length}</span>
          </div>
        </div>
      </CardContent>
    </Card>
  )
}
